"ui";
importClass(android.graphics.Color);
importClass(android.graphics.drawable.GradientDrawable);
// 数据
var storage = storages.create("autotouchSpw");
const project = require('./project.json');
// 开发配置
var isPulic = false;
//参数声明
var gamePackageName = "com.qqgame.mic";
var gameActivity = "com.qqgame.mic.YXSMainActivity";
var deviceWidth = device.width;
var deviceHeight = device.height;
var picJizhun = 1;
var picJizhunHeight = 1;
var floatyConsole; // 日志悬浮窗
var myLogStr = ""; // 重写打印
var version = project.versionName;   //版本号

var yanchi = 500; // 点击后停顿
var yanchi1 = 1000; // 点击前停顿
var yanchi2 = 2000; // 点击后停顿
var yanchi3 = 3000; // 点击后停顿
var yanchi5 = 5000; // 点击后停顿

var xinyufen = 100;

ui.layout(
    <ScrollView>
        <vertical>
            <appbar>
                <toolbar id="appTitle" title="道一科技" />
            </appbar>
            <Switch id="autoService" text="无障碍服务" checked="{{auto.service != null}}" padding="8 8 8 8" textSize="15sp" />
            <horizontal>
                <text text="  激活码：" gravity="left" />
                <input id="jihuoma" hint="请输入注册码" textSize="15sp" inputType="text" gravity="left" w="*" />
            </horizontal>
            <text text="   公告：" textColor="#E63F31" textSize="14sp" marginTop="8sp" />
            <text id="gonggao" text="见面发财，黄金万两! " textColor="#E63F31" textSize="15sp" paddingLeft="10sp" />
            <text text="   欢迎使用道一科技系列产品" gravity="left" marginTop="6sp" />
            <text autoLink="web" text="   官网：http://daoyikeji.com 备用网址： autotouch.top" gravity="left" />
            <text text="   淘宝：道一科技店" gravity="left" />
            <text text="   温馨提示：" gravity="left" marginTop="6sp" />
            <text text="   1.软件用于排位逃跑，在经典场刷信誉分；" gravity="left" />
            <text text="   2.老版本英雄杀版本：v3.31.0.1678；" gravity="left" />
            <horizontal>
                <text text="   系统提示：" gravity="left" />
                <checkbox id="支持" text="本软件无需root权限。" checked="true" />
            </horizontal>

            <horizontal>
                <text id="appVersion" text="   当前软件版本：  " gravity="left" />
                <text id="androidVer" textSize="15sp" />
            </horizontal>
            <horizontal marginTop="6sp">
                <button id="start" text="开始运行" layout_weight="1" style="Widget.AppCompat.Button.Colored" />
            </horizontal>

        </vertical>
    </ScrollView>
);

ui.androidVer.text("   本机安卓版本：" + device.release + "");
ui.appVersion.text("   当前软件版本：" + version + "     ");
ui.appTitle.title = "道一科技 - 刷排位 v " + version;
ui.autoService.on("check", function (checked) {
    if (checked && auto.service == null) {
        app.startActivity({
            action: "android.settings.ACCESSIBILITY_SETTINGS"
        });
    }
    if (!checked && auto.service != null) {
        auto.service.disableSelf();
    }
});
readconfig()
log(device.fingerprint)

//记录按键被按下时的触摸坐标
var x = 0, y = 0;
//记录按键被按下时的悬浮窗位置
var windowX, windowY;
// 悬浮窗
var floatyWindow;

function xuanfuFunc() {
    floatyWindow = floaty.window(
        <horizontal>
            <button id="floatyAction" text="运" textSize="9sp" w="20" h="20" margin="0sp" padding="0sp"></button>
            <button id="myExit" text="退出" textSize="8sp" w="30" h="15" bg="#02FE99" marginLeft="8sp" padding="0sp"/>
        </horizontal >
    );

    floatyWindow.setPosition(150, 60);

    floatyWindow.floatyAction.setOnTouchListener(function (view, event) {
        switch (event.getAction()) {
            case event.ACTION_DOWN:
                x = event.getRawX();
                y = event.getRawY();
                windowX = floatyWindow.getX();
                windowY = floatyWindow.getY();
                return true;
            case event.ACTION_MOVE:
                //移动手指时调整悬浮窗位置
                floatyWindow.setPosition(windowX + (event.getRawX() - x), windowY + (event.getRawY() - y));
                return true;
            case event.ACTION_UP:
                //手指弹起时如果偏移很小则判断为点击
                if (Math.abs(event.getRawY() - y) < 5 && Math.abs(event.getRawX() - x) < 5) {
                    floatyActionOnClick();
                }
                return true;
        }
        return true;
    });

    floatyWindow.myExit.on("click", function () {
        ui.finish()
    })

    floatyWindow.myExit.setVisibility(8);
    setBackgroundRoundRounded(floatyWindow.floatyAction, Color.YELLOW);
}

function setBackgroundRoundRounded(view, bloo) {
    gradientDrawable = new GradientDrawable();
    gradientDrawable.setShape(GradientDrawable.RECTANGLE);
    gradientDrawable.setColor(bloo);
    gradientDrawable.setCornerRadius(80);
    view.setBackground(gradientDrawable);
}


function floatyActionOnClick() {
    if (floatyWindow.floatyAction.getText() == '运') {
        threads.shutDownAll()
        setBackgroundRoundRounded(floatyWindow.floatyAction, Color.RED);
        floatyWindow.myExit.setVisibility(0);
        floatyWindow.floatyAction.setText('停');
    } else if (floatyWindow.floatyAction.getText() == '停') {
        mainFunc()
        floatyWindow.myExit.setVisibility(8);
        setBackgroundRoundRounded(floatyWindow.floatyAction, Color.GREEN);
        floatyWindow.floatyAction.setText('运');
        log("重启...")
    }
}


function saveconfig() {
    storage.put("jihuoma", ui.jihuoma.text());
    log('保存配置')
}

function readconfig() {
    ui.jihuoma.text(storage.get("jihuoma", ""));
}

// 悬浮窗
function xuanfuLogFunc() {
    floatyConsole = floaty.rawWindow(
        <frame gravity="left">
            <text id="myLog" text="日志" textColor="#ffffff" textSize="8sp" ellipsize="marquee" gravity="bottom" />
        </frame>
    );
    let w = 358 * picJizhun
    let h = 188 * picJizhun
    floatyConsole.setSize(w, h)
    floatyConsole.setPosition(5, device.width - h);
    floatyConsole.setTouchable(false)
    floatyConsole.myLog.text(" " + myLogStr + " ");
}

// 用户输出
function myLogFunc() {
    log(arguments)
    myLogStr += '\n' + String(arguments[0])
    //对控件的操作需要在UI线程中执行
    ui.run(function () {
        floatyConsole.myLog.text(" " + myLogStr + " ");
    });
}


ui.start.on("click", function () {
    log('屏幕分辨率', deviceWidth, deviceHeight)
    // 保存配置
    saveconfig()
    //程序开始运行之前判断无障碍服务
    if (auto.service == null) {
        toastLog("请先开启无障碍服务！");
        app.startActivity({
            action: "android.settings.ACCESSIBILITY_SETTINGS"
        });
        return;
    } else {
        log('已获取无障碍权限');
    }
    // 悬浮窗按钮
    if (!floaty.checkPermission()) {
        // 没有悬浮窗权限，提示用户并跳转请求
        toastLog("本脚本需要悬浮窗权限来显示悬浮窗，请在随后的界面中允许并重新运行本脚本。");
        floaty.requestPermission();
        return;
    } else {
        log('已获取悬浮窗权限');
    }
    // 右上悬浮窗
    xuanfuFunc()
    // 输出日志窗口
    xuanfuLogFunc()

    mainFunc();
});

// 请求服务器
function autoServerFunc() {
    let androidId = device.getAndroidId();
    var req = http.postJson("http://123.60.43.199:8866/main/v1/auto/yxsSpwApp", {
        activationCode: storage.get("jihuoma", ""),
        aap: "yxsSpw",
        deviceWidth: deviceWidth,
        deviceHeight: deviceHeight,
        brand: device.brand,
        versionCode: project.versionCode,
        release: device.release,
        sdkInt: device.sdkInt,
        androidId: androidId,
        fingerprint: device.fingerprint,
        // mac: device.getMacAddress(),
        // iMEI: device.getIMEI(),
        startTime: new Date().getTime()
    });
    var rJson = req.body.json();
    if (rJson.code != 200) {
        let message = rJson.message ? rJson.message : "服务异常请联系客服！";
        toastLog(message)
        sleep(2000)
        exit()
        sleep(1000)
        ui.finish()
    } else {
        // ui.gonggao.text(String(rJson.data))
        myLogFunc("服务成功注册！")
    }
}

// 主进程
function mainFunc() {
    threads.start(function () {
        log("新线程")
        // 检查无障碍服务是否已经启用，如果没有启用则跳转到无障碍服务启用界面，并等待无障碍服务启动；当无障碍服务启动后脚本会继续运行。
        auto.waitFor()
        sleep(1000)
        deviceWidth = device.width > device.height ? device.width : device.height;
        deviceHeight = device.height > device.width ? device.width : device.height;
        log('分辨率', deviceWidth, deviceHeight)
        picJizhun = deviceHeight / 1080;
        picJizhunHeight = deviceHeight / 1080;
        log('分辨率基准：', picJizhun)
        sleep(1000)

        //截图权限自动化安卓版本高于Android 9
        if (device.sdkInt > 27) {
            //等待截屏权限申请并同意
            threads.start(function () {
                if (device.brand == "HUAWEI") {
                    packageName('com.android.systemui').text('允许').waitFor();
                    sleep(yanchi)
                    text('允许').click();
                } else {
                    packageName('com.android.systemui').text('立即开始').waitFor();
                    sleep(yanchi)
                    text('立即开始').click();
                }
            });
        }
        sleep(yanchi)
        //申请截屏权限
        if (!requestScreenCapture(true)) {
            myLogFunc("请求截图失败");
            exit()
        }

        // 开启服务
        autoServerFunc();

        sleep(yanchi1)
        // 启动游戏
        var appPackName = currentPackage();
        myLogFunc("启动游戏", appPackName)
        if (appPackName != gamePackageName) {
            app.launchPackage(gamePackageName);
            myLogFunc("游戏启动中，请稍等...")
            sleep(2000)
            appPackName = currentPackage();
            if (appPackName == gamePackageName) {
                myLogFunc("游戏已打开，请稍等...")
            }
            if (isPulic) {
                sleep(yanchi5 * 3)
            } else {
                sleep(yanchi1)
            }
        } else {
            myLogFunc("游戏正在运行");
        }


        // while (!dengchupaiFunc()) {
        //     sleep(2000)
        // }


        // xuanjiangaFunc()

        // taopaoFunc()

        // return
        log(1)
        let thisImgs = images.read("./res/paiweisai.png");
        log(2)
        thisImgs = images.scale(thisImgs, picJizhun, picJizhunHeight);
        log(3)
        let p = findImage(captureScreen(), thisImgs, { threshold: 0.8 });
        log(4)
        myLogFunc("捕获成功")
        log(5)
        thisImgs.recycle();
        log(6)
        if (p) {
            click(80, 80)
            sleep(1000)

            // 读取
            let thisImgs1 = images.read("./res/xinyuzhi.png");
            thisImgs1 = images.scale(thisImgs1, picJizhun, picJizhunHeight);
            let p1 = findImage(captureScreen(), thisImgs1, { threshold: 0.8 });
            myLogFunc("读取信誉值")
            thisImgs1.recycle();
            if (p1) {
                let guox = p1.x + 153*picJizhun
                let clip = images.clip(captureScreen(), guox, p1.y, 200, 65);
                let result = paddle.ocrText(clip);
                log('信誉值',result)
                if (result) {
                    let num = result[0]
                    num = Number(num)
                    xinyufen = num
                }
                
                // 关闭
                let thisImgs2 = images.read("./res/closeRen.png");
                thisImgs2 = images.scale(thisImgs2, picJizhun, picJizhunHeight);
                let p2 = findImage(captureScreen(), thisImgs2, { threshold: 0.8 });
                myLogFunc("关闭个人信息")
                thisImgs2.recycle();
                if (p2) {
                    click(p2.x, p2.y)
                    sleep(2000)

                    needPaiweiFunc();

                    // 循环运行
                    while (true) {
                        myLoopFunc()
                    }
                    
                    myLogFunc("幸运分不足！！")
                }
            }
        }
    })
}

function myLoopFunc() {
    myLogFunc('信誉分' + xinyufen)
    if (drPaiweiFunc() && xinyufen >= 90) {
        sleep(1000)
        myLogFunc("等待选将")
        while (!dengdaixuanjiangFunc()) {
            sleep(3000)
        }

        xuanjiangaFunc()


        while (!dengchupaiFunc()) {
            sleep(3000)
        }


        xuanjiangaFunc()

        taopaoFunc()

    }else{
        // 不文明行为

        while (xinyufen < 100) {
            myLogFunc('刷信誉分' + xinyufen)

            fanhuiFunc()

            jingdiancahngFunc()
    
            jichuyxFunc()
    
            taopaoFunc1() 

            sleep(1000)
        }
        myLogFunc("信誉分够了！")

        fanhuiFunc()
        
        let thisImgs = images.read("./res/paiweisai.png");
        thisImgs = images.scale(thisImgs, picJizhun, picJizhunHeight);
        let p = findImage(captureScreen(), thisImgs, { threshold: 0.8 });
        myLogFunc("捕获成功")
        thisImgs.recycle();
        if (p) {
            click(80, 80)
            sleep(1000)
            // 读取
            let thisImgs1 = images.read("./res/xinyuzhi.png");
            thisImgs1 = images.scale(thisImgs1, picJizhun, picJizhunHeight);
            let p1 = findImage(captureScreen(), thisImgs1, { threshold: 0.8 });
            myLogFunc("读取信誉值")
            thisImgs1.recycle();
            if (p1) {
                let guox = p1.x + 153*picJizhun
                let clip = images.clip(captureScreen(), guox, p1.y, 200, 65);
                let result = paddle.ocrText(clip);
                log('信誉值',result)
                if (result) {
                    let num = result[0]
                    num = Number(num)
                    xinyufen = num
                }
                myLogFunc("更新信誉值"+xinyufen)
                // 关闭
                let thisImgs2 = images.read("./res/closeRen.png");
                thisImgs2 = images.scale(thisImgs2, picJizhun, picJizhunHeight);
                let p2 = findImage(captureScreen(), thisImgs2, { threshold: 0.8 });
                myLogFunc("关闭个人信息")
                thisImgs2.recycle();
                if (p2) {
                    click(p2.x, p2.y)
                    sleep(2000)
                }
            }
        }
    }
}


function needPaiweiFunc() {
    let thisImgs2 = images.read("./res/paiweisai.png");
    thisImgs2 = images.scale(thisImgs2, picJizhun, picJizhunHeight);
    let p2 = findImage(captureScreen(), thisImgs2, { threshold: 0.8 });
    thisImgs2.recycle();
    if (p2) {
        myLogFunc("进入排位赛")
        click(p2.x, p2.y)
        sleep(2000)        
    }
}

function drPaiweiFunc() {
    let thisImgs2 = images.read("./res/danrenpaiwei.png");
    thisImgs2 = images.scale(thisImgs2, picJizhun, picJizhunHeight);
    let p2 = findImage(captureScreen(), thisImgs2, { threshold: 0.8 });
    thisImgs2.recycle();
    log('drPaiweiFunc',p2)
    if (p2) {
        myLogFunc("单人排位")
        click(p2.x, p2.y)
        sleep(2000)
        
        let thisImgs3 = images.read("./res/danrenpaiwei.png");
        thisImgs3 = images.scale(thisImgs3, picJizhun, picJizhunHeight);
        let p3 = findImage(captureScreen(), thisImgs3, { threshold: 0.8 });
        thisImgs3.recycle();
        if (p3) {
            return false
        }else{
            return true
        }
    }else{
        myLogFunc("寻找单人排位")
        taopaoFunc1()
        fanhuiFunc()
        needPaiweiFunc()
        drPaiweiFunc()
    }
}

function dengdaixuanjiangFunc() {
    let thisImgs2 = images.read("./res/xuanzeyingxiong.png");
    thisImgs2 = images.scale(thisImgs2, picJizhun, picJizhunHeight);
    let p2 = findImage(captureScreen(), thisImgs2, { threshold: 0.8 });
    thisImgs2.recycle();
    if (p2) {
        myLogFunc("可以选将")
        click(p2.x, p2.y)
        sleep(2000)
        return true;     
    }else{
        return false;    
    }
}

function xuanjiangaFunc() {
    let thisImgs4 = images.read("./res/xiang.png");
    thisImgs4 = images.scale(thisImgs4, picJizhun, picJizhunHeight)
    let result = images.matchTemplate(captureScreen(), thisImgs4, { threshold: 0.8, max: 12 });
    thisImgs4.recycle();
    log('选将',result)
    if (result.matches.length) {
        let points = result.sortBy("left-right").points;
        for (let index = 0; index < points.length; index++) {
            let match = points[index];
            myLogFunc('选将')
            sleep(yanchi)
            click(match.x+100, match.y)
        }
    }
}

function dengchupaiFunc() {
    let thisImgs2 = images.read("./res/qipan.png");
    thisImgs2 = images.scale(thisImgs2, picJizhun, picJizhunHeight);
    let p2 = findImage(captureScreen(), thisImgs2, { threshold: 0.8 });
    thisImgs2.recycle();
    if (p2) {
        myLogFunc("可以逃跑")
        sleep(2000)
        return true;     
    }else{
        myLogFunc("等待开始")
        return false;    
    }
}

function taopaoFunc() {
    let thisImgs2 = images.read("./res/caidan.png");
    thisImgs2 = images.scale(thisImgs2, picJizhun, picJizhunHeight);
    let p2 = findImage(captureScreen(), thisImgs2, { threshold: 0.8 });
    thisImgs2.recycle();
    if (p2) {
        myLogFunc("点击菜单")
        click(p2.x, p2.y)
        sleep(2000) 
        
        let thisImgs3 = images.read("./res/tuichu.png");
        thisImgs3 = images.scale(thisImgs3, picJizhun, picJizhunHeight);
        let p3 = findImage(captureScreen(), thisImgs3, { threshold: 0.8 });
        thisImgs3.recycle();
        if (p3) {
            myLogFunc("点击退出")
            click(p3.x, p3.y)
            sleep(2000)
            
            let thisImgs4 = images.read("./res/quedinga.png");
            thisImgs4 = images.scale(thisImgs4, picJizhun, picJizhunHeight);
            let p4 = findImage(captureScreen(), thisImgs4, { threshold: 0.8 });
            thisImgs4.recycle();
            if (p4) {
                myLogFunc("确定退出")
                click(p4.x, p4.y)
                xinyufen = xinyufen - 5
                sleep(2000)
            }
        }
    }
}

function taopaoFunc1() {
    let thisImgs2 = images.read("./res/caidan.png");
    thisImgs2 = images.scale(thisImgs2, picJizhun, picJizhunHeight);
    let p2 = findImage(captureScreen(), thisImgs2, { threshold: 0.8 });
    thisImgs2.recycle();
    if (p2) {
        myLogFunc("点击菜单")
        click(p2.x, p2.y)
        sleep(2000) 
        
        let thisImgs3 = images.read("./res/tuichu.png");
        thisImgs3 = images.scale(thisImgs3, picJizhun, picJizhunHeight);
        let p3 = findImage(captureScreen(), thisImgs3, { threshold: 0.8 });
        thisImgs3.recycle();
        if (p3) {
            myLogFunc("点击退出")
            click(p3.x, p3.y)
            sleep(1000)
            
            let thisImgs4 = images.read("./res/quedinga.png");
            thisImgs4 = images.scale(thisImgs4, picJizhun, picJizhunHeight);
            let p4 = findImage(captureScreen(), thisImgs4, { threshold: 0.8 });
            thisImgs4.recycle();
            if (p4) {
                myLogFunc("确定退出")
                click(p4.x, p4.y)
                xinyufen = xinyufen + 1
                sleep(2000)
            }
        }
    }
}


function fanhuiFunc() {
    let thisImgs2 = images.read("./res/fanhui.png");
    thisImgs2 = images.scale(thisImgs2, picJizhun, picJizhunHeight);
    let p2 = findImage(captureScreen(), thisImgs2, { threshold: 0.8 });
    thisImgs2.recycle();
    if (p2) {
        myLogFunc("返回主页")
        click(p2.x, p2.y)
        sleep(2000)        
    }
}

function jingdiancahngFunc() {
    let thisImgs2 = images.read("./res/jingdiancahng.png");
    thisImgs2 = images.scale(thisImgs2, picJizhun, picJizhunHeight);
    let p2 = findImage(captureScreen(), thisImgs2, { threshold: 0.8 });
    thisImgs2.recycle();
    if (p2) {
        myLogFunc("经典场")
        click(p2.x+50, p2.y+20)
        sleep(2000)        
    }
}

function jichuyxFunc() {
    let thisImgs2 = images.read("./res/jichuyx.png");
    thisImgs2 = images.scale(thisImgs2, picJizhun, picJizhunHeight);
    let p2 = findImage(captureScreen(), thisImgs2, { threshold: 0.8 });
    thisImgs2.recycle();
    if (p2) {
        myLogFunc("基础场")
        click(p2.x, p2.y)
        sleep(2000)        
    }
}






